// packageA/pages/repairList/repairList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
//去掉末尾的0
const regexp=/(?:\.0*|(\.\d+?)0+)$/;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词  
    searchValue:'',
    //删除确认框
    showDelete:false,
    //删除的id
    deleteId:null, 
    //状态筛选
    optionState:[
      {text: '所有状态', value: -1},
      {text: '未完成', value: 0},
      {text: '已完成', value: 1}
    ],
    valueState: -1,
    //接单人筛选
    optionReceive:[
      {text: '我接单的', value: 1},
      {text: '所有记录', value: 2},     
    ],
    valueReceive: null,
    //当前登录用户
    user:null,
    //用户权限
    authority:null,
    //更改接单人弹出框
    showReceive:false,
    //当前操作的数据
    currentObj:null,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    let authority=app.globalData.authority;

    this.setData({ 
      user: user,
      authority: authority
    })

    //设置valueReceive（平台售后人员查自己接单的，其他查所有）
    if(authority.iot.afterSales && authority.iot.afterSales.afterBtn){
      this.setData({ 
        valueReceive: 1
      })
    }else{
      this.setData({ 
        valueReceive: 2
      })
    }

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);

      console.log('维修工单传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      }) 
    }

    //获取列表数据
    this.getList();    
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
      selectFields: ["id", "orderNo", "equipmentNo", "depart", "project", "equipmentId", "receiver", "state", "costs","processingTime", "expirationTime", "serviceDetails", "businessType", "logistics", "repairInfo","completeDate", "closeOrderDate", "faultType", "processMode", "processResult", "trueFault", "pic","memberTypeName","remark","callRecord","dataAuthority"],
      sort: {
        processingTime: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    } 
    
    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      //是否独立售后
      if(app.globalData.afterSaleSelf){
        dataObj.appId=app.globalData.myAppId;
      }else{
        dataObj.appId=[2,3,null];
      }
    }else{
        dataObj.appId=[2,3,null];
    }

    //单个设备的记录
    if(this.data.paramObj.equipmentId){
      dataObj.equipmentId=this.data.paramObj.equipmentId;
    }

    //设备编码
    if(this.data.searchValue){
      dataObj.equipmentNo='%' +this.data.searchValue+ '%';
    }
    
    //筛选状态
    if(this.data.valueState!=-1){
      dataObj.state=this.data.valueState;
    }

    //接单人   
    if(this.data.valueReceive==1){
      dataObj['receiver.id']=this.data.user.id;
    }

    let param = {
      isAuth: true,
      className: 'afterSaleMaintainOrder',
      data: dataObj 
    }

    CommonService.goFindList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;       

        result.forEach(item => {
          //状态
          switch(item.state){
            case 0:
              item.stateWord='未完成';
              item.stateClass='c-1';
              break;
            case 1:
              item.stateWord='已完成';
              item.stateClass='c-2';
              break;
          }

          //业务类型
          if(item.businessType){       
            switch(item.businessType){
              case 1:
                item.self_businessType='销售';
                break;
              case 2:
                item.self_businessType='租赁-授信';
                break;
              case 3:
                item.self_businessType='租赁-非授信';
                break;
              case 4:
                item.self_businessType='试机';
                break;
              case 5:
                item.self_businessType='存量改造';
                break;
            }
          }
       
          //工单费用
          let totalCost=0.0;
          if(item.logistics && item.logistics.length) {
            item.logistics.forEach(l => {
              totalCost += Number(l.freight);
              if(l.parts.length){
                l.parts.forEach(p => {
                  totalCost += Number(p.salePrice) * p.num;
                });
              }   
            });
          }
         
          if(item.costs && item.costs.length) {
            item.costs.forEach(l => {              
              totalCost += Number(l.cost);
            });
          }

          //保留两位小数并去掉末尾的0
          item.totalCost=totalCost.toFixed(2).replace(regexp,'$1');
        });

        console.log('维修工单列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //选择状态
  onChangeState({detail}) {
    this.setData({
      valueState: detail
    })
    this.refreshListAndPage();
  },

  //选择接单人
  onChangeReceive({detail}) {
    this.setData({
      valueReceive: detail
    })
    this.refreshListAndPage();
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  }, 
  
  //跳转编辑(接待信息)
  goToEdit(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      id: detail.id
    }

    wx.navigateTo({
			url: "/packageA/pages/repairEdit/repairEdit?paramObj="+JSON.stringify(obj)
		})
  },

  //跳转物流
  goToLogistics(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      repairId: detail.id,
      equipmentNo: detail.equipmentNo
    }

    wx.navigateTo({
			url: "/packageA/pages/repairLogistics/repairLogistics?paramObj="+JSON.stringify(obj)
		})
  },

  //添加报修
  goToAdd(){
    let obj={
      repairType: 216,
      equipmentId: this.data.paramObj.equipmentId
    }

    wx.navigateTo({
			url: "/pages/repairAdd/repairAdd?paramObj="+JSON.stringify(obj)
		})
  },

  //费用
  goToCosts(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      repairId: detail.id,
      equipmentNo: detail.equipmentNo
    }

    wx.navigateTo({
			url: "/packageA/pages/repairCosts/repairCosts?paramObj="+JSON.stringify(obj)
		})
  },

  //详情
  goToLook(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      repairId: detail.id,
      equipmentNo: detail.equipmentNo
    }

    wx.navigateTo({
			url: "/packageA/pages/repairDetail/repairDetail?paramObj="+JSON.stringify(obj)
		})
  },

  //闭单
  onClose(e){
    let detail=e.currentTarget.dataset.detail;

    //接待信息必填
    if(detail.faultType && detail.processMode && detail.trueFault && detail.processResult){
    }else{
      Toast.fail('接待信息不完整');
      return;
    }  

    Dialog.confirm({
      title: '确定关闭当前工单吗',
      message:'状态将更新为已完成',
      confirmButtonText:'关闭',
      cancelButtonText:'取消'
    }).then(() => {  
      let param={
        id: detail.id
      }

      CommonService.closeMaintainOrder(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已关闭');  

          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  //删除
  onDelete(e){
    Dialog.confirm({
      title: '确定删除当前工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不删除了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        id: detail.id,
        equipmentId: detail.equipmentId,
      }

      CommonService.delMaintainOrder(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已删除');  

          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  //拨打电话
  onCall(e){
    let userName=this.data.user.userName;
    let detail=e.currentTarget.dataset.detail;    

    //打电话
    wx.makePhoneCall({
      phoneNumber: detail.repairInfo.phone
    })

    //保存点击记录
    let callRecord=[];
    if(detail.callRecord && detail.callRecord.length){
      callRecord=detail.callRecord;
    }
    callRecord.push({
      time: util.timeFormat(new Date()),
      name: userName
    });  

    let param={
      className:'afterSaleMaintainOrder',
      data:{
        id: detail.id,
        callRecord: callRecord
      }
    }

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })  
  },

  //转单
  onChangeType(e){
    Dialog.confirm({
      title: '确定将当前工单转为耗材工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不转了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        id: detail.id,
        equipmentNo: detail.equipmentNo,
        equipmentId: detail.equipmentId,
        depart: detail.depart,
        project: detail.project,
        orderType: {
          id: 217,
          name: "耗材工单",
        },
        memberTypeName: detail.memberTypeName,
        repairMan: {
          name: detail.repairInfo.name,
          phone: detail.repairInfo.phone,
        },
        address: detail.repairInfo.address,
        repairDate: util.timeFormat(detail.repairInfo.date),
        createDate: detail.repairInfo.createDate,
        dataSource: 2,
        pic: detail.repairInfo.pic,
        repairQuestion: detail.repairInfo.question,
        businessType: detail.businessType,
        state: 0,
        appId: [app.globalData.myAppId],
        dataAuthority: detail.dataAuthority
      }

      CommonService.changeToConsumable(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){ 
          Dialog.confirm({
            title: '操作成功',
            confirmButtonText:'查看耗材工单',
            cancelButtonText:'留在本页'
          }).then(() => {
            //跳转到售后记录
            wx.reLaunch({
              url: '/packageA/pages/consumableList/consumableList'
            })
          }).catch(() => {
            //刷新列表和页码
            this.refreshListAndPage();
          });
          
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  //显示更改接单人员
  onShowReceive(e){  
    this.setData({
      showReceive: true,
      currentObj: e.currentTarget.dataset.detail
    })
  },

  //隐藏更改接单人员
  onCloseReceive(){
    this.setData({
      showReceive: false
    })
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //接单人
    if(field=='receiver'){
      this.setData({
        selectTitle: '接单人员',
        showSelectSearch: true
      })
      this.getStaffList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: ''
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //接单人
    if(selectField=='receiver'){
      obj='currentObj.receiver';
    }  

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },  

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //接单人
    if(selectField=='receiver'){
      this.getStaffList();
    }
  },

  //查询人员
  getStaffList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'servicePersonal',
      data: {
        searchAll: true,
        type: 33,
        selectFields: ['serviceName','telephone','userId']
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.serviceName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.serviceName,
            id: item.userId,
            obj: {
              id: item.userId,
              name: item.serviceName,
              phone: item.telephone
            }
          });
        });
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //确定更改接单人
  onConfirmReceive(){
    let current=this.data.currentObj; 

    //接单人在u_service_personal表中有userId的才能转，否则转完了无法编辑
    if(current.receiver.id){
      this.onCloseReceive();

      Dialog.confirm({
        title: '确定更改接单人吗',
        confirmButtonText:'确定',
        cancelButtonText:'取消'
      }).then(() => {
        let param={
          className:'afterSaleMaintainOrder',
          data:{
            id: current.id,
            receiver: current.receiver
          }
        }  

        CommonService.goSave(param).then(res=>{
          if (res.statusCode == 200 && res.data.success == true){
            //刷新列表和页码
            this.refreshListAndPage();
          }else{
            Toast.fail('操作失败');
          }
        }).catch((error) => {
          Toast.fail('操作失败');
        })

      }).catch(() => {
      });
    }else{
      Toast.fail('无法转单，人员信息缺失，请到管理后台维护');
    }  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})